/*function createNotice(text,linkedEle,type){
	var elobj = document.createElement('p');
	elobj.className = 'notice error';
	elobj.innerHTML = text;
	elobj.id = linkedEle+'-notice';

	var pn = document.getElementById(linkedEle).parentNode;
	pn.appendChild(elobj);
}*/



/*** 表单检查 ***/

var formCheck = {
	checkGroup:{
		0: ['theme','theme_description'],
		1: ['vote_type','options'],
		2: ['time', 'member_uplimit','will_notice'],
	},
	check: function(nameList){
		var res = true;
		if(!Array.isArray(nameList)){
			nameList = new Array(nameList.toString());
		}
		var array_index = nameList.length;
		for(var i=0; i < array_index; i++){
			var judgeData = (nameList[i]=='options')?this.checkOptions():this.fieldFilter(nameList[i]);
			//options 判断特殊处理
			//取得返回的错误信息
			if(judgeData.status){
				this.removeNotice(judgeData.msgContainer);
			}else{
				res = false;
				this.addNotice(judgeData.msgContainer, judgeData.msgText);
			}
		}
		return res;
	},
	showFormCheckErrorMsg: function(){
		var para = {
			title: '嗯…',
			content: '你的表单填写还是有些问题',
			buttons: [{text:'再检查一下', action:'msgBox.hide();'}]
		};
		msgBox.pop(para);
	},
	fieldFilter: function(fieldName){
		var formObj = document.getElementById('new-poll');
		var els = document.getElementsByName(fieldName);
		if(els.length == 0) return false;
		var el = els[0];

		var judgeResult = {	// 存放错误数据
			'status':true,	// 表单域是否合法
			'msgText':'',	// 错误提示消息
			'msgContainer':''	// 错误提示容器：使用ID
		}

		switch(fieldName){
		case 'theme':
			judgeResult.msgContainer = 'notice_theme';
			if(el.value.length == 0){
				judgeResult.msgText= '请输入投票标题';
				judgeResult.status = false;
			}else if(el.value.length > 20){
				judgeResult.msgText= '投票标题不可超过20字';
				judgeResult.status = false;
			}
			break;

		case 'theme_description':
			judgeResult.msgContainer = 'notice_theme_description';
			if(el.value.length>100){
				judgeResult.msgText= '投票描述不多于100字';
				judgeResult.status = false;
			}
			break;

		case 'vote_type':
			judgeResult.msgContainer = 'notice_vote_type';
			var hasChecked = false;
			for(var i=0; i<els.length; i++){
				hasChecked = hasChecked || els[i].checked;
			}
			if(!hasChecked){
				judgeResult.msgContainer = 'notice_vote_type';
				judgeResult.msgText= '请选择投票类型';
				judgeResult.status = false;
			}
			break;

		case 'day':
		case 'hour':
		case 'minute':
			//var opo = el.options[el.selectedIndex];
			judgeResult.msgContainer = 'notice_time';
			if(el.value == ''){
				judgeResult.msgText= '请选择时间';
				judgeResult.status = false;
			}
			break;

		case 'member_uplimit':
			judgeResult.msgContainer = 'notice_member_uplimit';
			if(parseInt(el.value)<=0){
				judgeResult.msgText= '请输入合法数值';
				judgeResult.status = false;
			}
			break;

		case 'will_notice':
			//var opo = el.options[el.selectedIndex];
			judgeResult.msgContainer = 'notice_will_notice';
			if(el.value===undefined){
				judgeResult.msgText= '请选择提醒';
				judgeResult.status = false;
			}
			break;
		}

		return judgeResult;
	},
	addNotice: function(elemId, message){
		var el = document.getElementById(elemId);
		if(!el) return false;
		el.classList.add('notice-show');
		el.classList.remove('notice-hidden');
		el.innerHTML = message;
	},
	removeNotice: function(elemId){
		var el = document.getElementById(elemId);
		if(!el) return false;
		el.classList.add('notice-hidden');
		el.classList.remove('notice-show');
		el.innerHTML = '';
	},
	checkOptions: function(){
		//选项的判断比较特殊，判断分开写
		var judgeResult = {	// 存放错误数据
			'status':true,	// 表单域是否合法
			'msgText':'',	// 错误提示消息
			'msgContainer':'notice_options'	// 错误提示容器：使用ID
		}

		var optionFields = document.getElementsByName('option[]');
		if(optionFields.length < 2){
			judgeResult.status = false;
			judgeResult.msgText = '请输入至少两个选项';
		}else{
			for(var i=0; i < optionFields.length; i++){
				var fv = optionFields[i].value.trim();
				if(fv.length == 0){
					judgeResult.status = false;
					judgeResult.msgText = '请输入选项内容';
					break;
				}
			}
		}
		return judgeResult;
	},
	checkAll: function(){
		return this.check(['theme','theme_description','vote_type','options','day','minute','hour', 'member_uplimit']);
	}
}


function addEvents(){
	/*var getCallback = function(f){
		return function(){fieldCheck(f);}
	}

	var fieldList = ['title','description','people'];
	for(var i=0;i<fieldList.length;i++){
		var f = fieldList[i];
		document.getElementById('poll-'+f).addEventListener('blur',getCallback(f));
	}

	fieldList = ['notice','timem','timeh','timed','type'];
	for(var i=0;i<fieldList.length;i++){
		var f = fieldList[i];
		document.getElementById('poll-'+f).addEventListener('change',getCallback(f));
	}

	document.getElementById('new-poll').addEventListener('submit',function(e){
		//console.log(e);
		if(checkAllField()){
			return true;
		}else{
			e.preventDefault()
			return false;
		}
	}
	);*/
}

//已废弃
var checkAllField = function(){
	var fieldList = ['title','description','people','notice','timem','timeh','timed','type'];
	var result = true;
	for(var i=0;i<fieldList.length;i++){
		var f = fieldList[i];
		if(!fieldCheck(f)){
			result = false;
		}
	}

	var optionFields = document.getElementsByClassName('option-text');
	if(optionFields.length<=2){
		createNotice('请输入至少两个选项','option','error');
		result = false;
	}else{
		for(var i=0; i<optionFields.length-1; i++){
			var fv = optionFields[i].value;
			fv = fv.replace(/\s/g,'');
			if(fv.length==0){
				result = false;
				createNotice('请输入选项内容','option','error');
				break;
			}
		}
	}

	if(!result){
		//alert('请先完整填写');
		document.getElementsByClassName('conspicuous-error')[0].style.fontSize = null;
	}

	return result;
}


function addOption(){
	var listObj = document.getElementById('table-form');
	var modenode = document.getElementById('option-con-0');
	var newnode = modenode.cloneNode(true);
	newnode.id=null;
	var continp = newnode.getElementsByClassName('option-text')[0];
	continp.value= '';
	continp.name = 'option[]'
	
	modenode.parentNode.insertBefore(newnode,document.querySelector('#option-add-btn'));
	continp.focus();
	continp.disabled = false;
	
	return {'node':newnode,'text':continp}; 
}

function removeOption(el){
	if(el.id=='option-con-0') return false;
	el.parentNode.removeChild(el);
}

//add new option and focus it
function addItem(){
	var elc = addOption();
	elc.text.focus();
}

function delItem(ob){
	removeOption(ob.parentNode);
}


/** send post **/
function sendFormPost(){
	var postData = $('#new-poll').serialize();
	postJSON(API_URL,postData,sendPostCallback);
	loadingBox.show();
}

function sendPostCallback(data,status){
	//console.log(data);
	setShareData(data);
	loadingBox.hide();
}

function submitForm(){
	if(formCheck.checkAll.call(formCheck)){
		sendFormPost();
	}
}


/** share section **/
function setShareData(data){
	document.getElementById('share').style.display = 'block';
	document.getElementById('new').style.display = 'none';
	document.getElementById('share-id').innerHTML = data['room_id']; 
	var h = location.href;
	var url = h.substring(0,h.lastIndexOf('/')+1)+'poll.htm#'+data['room_id']+'@'
	//var url = h.substring(0,h.lastIndexOf('/')+1)+'poll.htm#room_id_key='+idNumberCoder.encode(data['room_id'])+'';
	document.getElementById('share-url').value = url;

	document.title = '分享投票 | WeVote';

	history.pushState({name:'sharedLink'}, 'WeVote join vote !', url);

	/*//var postData = getPostData();
	msgBox.pop({
		title:'新建投票成功',
		content:'快去和好友们分享你的投票',
		buttons:[
			{
				text:'分享投票',
				action:"msgBox.hide();history.pushState({name:'sharedLink'}, 'WeVote join vote !', '"+url+"');",
			}
		],
		icon:'success',
	});*/
}

/*
function initWxShare(){
	//http://weixin.bigtech.cc/service/jssdk_config
    try {
        if (typeof(wx) == "undefined") {
            return false;
        }
    } catch(e) {}

	getJSON('http://weixin.bigtech.cc/service/jssdk_config',function(rawData){
		var data = JSON.parse(rawData);
		wx.config({
			debug: true,
			appId: data['appid'], // 必填，公众号的唯一标识
			timestamp: data['timestamp'], // 必填，生成签名的时间戳
			nonceStr: data['noncestr'], // 必填，生成签名的随机串
			signature: data['signature'],// 必填，签名，见附录1
			jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
		});
		wx.ready(function(){window.wxReady = true;});
	});
}

function setWxShare(data){
	if(!window.wxReady) return false;
	//set api data & para
	wx.onMenuShareAppMessage({
		title: data['title'],
		desc: '微信投票 - WeVote', // 分享描述
		link: data['link'], // 分享链接
		type: 'link',
	});
	return true;
}*/


/*********** Swipier ************/
var dragStartPos = -1 , dragEndPos = -1;
var previousStyleLeft='0%';
var activeDrag = false;
var dragStartTime, dragEndTime;

function getPropertyValue(inp){
}

function proPval(inp){
	return inp.replace(/[a-zA-Z%()]/g,'');
}

function getDragStartPos(e){
	var scrollPos = window.pageXOffset || document.body.scrollLeft;
	var posx = (e.clientX || e.touches[0].clientX) + scrollPos;
	dragStartPos = posx;
	dragStartTime = Date.now();
	//console.log(dragStartPos,scrollPos);
	previousStyleLeft = bleo.style.transform;
	bleo.style.transitionDuration = '0s';
	//bleo.classList.add('swiper-drag-active');
}

function getEndPos(e){
	var cnum = parseInt(bleo.dataset.currentIndex);

	if(dragStartPos==-1) return false;

	var scrollPos = window.pageXOffset || document.body.scrollLeft;
	//console.log(dragStartPos,e);
	//Get touch position  when touching ending
	var touchPos = e.clientX || ((e.touches && e.touches.length)?e.touches[0].clientX:undefined) || ((e.changedTouches && e.changedTouches.length)?e.changedTouches[0].clientX:0);
	var posx = touchPos + scrollPos;
	dragEndPos = posx;
	//console.log(dragStartPos,e);
	////*/

	var speed = (dragEndPos-dragStartPos)/(Date.now() - dragStartTime);
	console.log(speed);
	if(Math.abs(speed) > 0.3 && Math.abs(speed) < 2000){//high speed --- move to next card directly
		bleo.style.transitionDuration = null;
		swipeBlock(cnum + (speed>0?-1:1) );
		//window.scrollTo(0,0);
	//}else if(speed == 0 || speed >200){ //If the event is to click btn
		//Do noting
	}else{
		var cp = parseInt(proPval(bleo.style.transform));
		console.log('cp'+proPval(bleo.style.transform));
		bleo.style.transitionDuration = null;
		swipeBlock(Math.round(-cp/100)+1);
	}
	dragEndPos = dragStartPos = -1;
	activeDrag = false;
	//
	document.getElementById('swiper-flow').classList.remove('swiper-drag-active');
}


function getDragAction(e){

	if(dragStartPos==-1) return false;
	var bnum = parseInt(bleo.dataset.totalIndex || 1);
	var cnum = parseInt(bleo.dataset.currentIndex || 1);

	var scrollPos = window.pageXOffset || document.body.scrollLeft;
	var posx = (e.clientX || e.touches[0].clientX) + scrollPos;
	//dragStartPos = dragEndPos;
	dragEndPos = posx;

	var viewWidth = document.getElementById('swiper-flow').clientWidth;

	//move block line
	var speed = (dragEndPos-dragStartPos)/(Date.now() - dragStartTime);
	//console.log(speed);
	if(Math.abs(speed) > 3 && Math.abs(speed) < 2000){//high speed --- move to next card directly
		//bleo.style.transitionDuration = null;
		//swipeBlock(cnum + (speed>0?-1:1) );
	}else{
		if(Math.abs((dragEndPos - dragStartPos)/viewWidth*100) > 10 || activeDrag) {
			e.preventDefault();
			activeDrag = true;
			bleo.style.transitionDuration = '0s';
			console.log('ww'+previousStyleLeft);
			bleo.style.transform = 'translateX('+(parseInt(proPval(previousStyleLeft)) + (dragEndPos - dragStartPos)/viewWidth*100)+'%)';
			document.getElementById('swiper-flow').classList.add('swiper-drag-active');
		}
	}
}


function swipeBlock(index){
	var blockLine = document.getElementById('swiper-line');
	var blockNum = blockLine.getElementsByClassName('swiper-block').length;
	index = index<=0 ? 1 : (index>blockNum?blockNum:index);

	blockLine.style.transform = 'translateX(-'+(index-1)+'00%)';
	if(blockLine.dataset.currentIndex != index){
		blockLine.dataset.currentIndex = index;
		window.scrollTo(0,0);
	}
	blockLine.dataset.totalIndex = blockNum;
	blockLine.offsetHeight;

	setDots(index);
	//window.scrollTo(0,0);
}

function setDots(index) {
	var dotsList = document.getElementById('nav-dots').getElementsByTagName('span');
	console.log('DOTS'+index);
	for(var i=0; i<dotsList.length; i++) {
		if(index-1 == i){
			dotsList[i].className += ' active';
		}else {
			dotsList[i].className = dotsList[i].className.replace('active','');
			dotsList[i].className = 'single-dot';
		}
	}
}


